// Copyright 2011 Bryan McKelvey, MIT License

/**
 * @fileoverview Settings
 * @author bryan.mckelvey@gmail.com (McKelvey Bryan)
 */

/**
 * @constructor
 */
var Settings = (function(){
	/**
	 * Default values for settings that must have a value
	 * @final
	 * @type Object
	 */
	var DEFAULTS = {
		language: 'default',
		sync: false,
		updateFrequency: 60000
	};
	
	/**
	 * Loads a value from local storage
	 * @param {string} key The name of the parameter
	 * @returns The value requested
	 */
	function get(key){
		return JSON.parse(localStorage[key]);
	};
	
	/**
	 * Saves a value to local storage
	 * @param {string} key The name of the parameter
	 * @param {Object} value The value to store
	 * @returns The current object
	 */
	function set(key, value){
		localStorage[key] = JSON.stringify(value);
		return Settings;
	};

	return {
		/**
		 * Gets or sets the column data in local storage
		 * @param {Object} value Column data
		 * @returns The value requested or the current object
		 */		
		columns: function(value){
			return (value !== undefined) ? set("columns", value) : get("columns");			
		},
		
		load: function(){
			$.each(DEFAULTS, function(key, defaultValue){
				try {
					var temp = JSON.parse(localStorage[key])
					if (typeof temp !== typeof defaultValue || temp === undefined) {
						set(key, defaultValue)
					}
				} catch(e) {
					set(key, defaultValue);
				}
			});
		},
		
		/**
		 * Gets or sets the update frequency in local storage
		 * @param {Object} value Frequency in milliseconds
		 * @returns The value requested or the current object
		 */
		frequency: function(value){
			return (value !== undefined) ? set("updateFrequency", value) : get("updateFrequency");			
		},

		/**
		 * Gets or sets the language in local storage
		 * @param {Object} value Valid locale code
		 * @returns The value requested or the current object
		 */
		language: function(value){
			return (value !== undefined) ? set("language", value) : get("language");			
		},
		
		/**
		 * Gets or sets the portfolios in local storage
		 * @param {Object} value Portfolio data
		 * @returns The value requested or the current object
		 */
		portfolios: function(value){
			return (value !== undefined) ? set("portfolios", value) : get("portfolios");			
		},

		/**
		 * Gets or sets whether bookmark sync is enabled in local storage
		 * @param {Object} value Whether bookmark sync is enabled
		 * @returns The value requested or the current object
		 */
		sync: function(value){
			return (value !== undefined) ? set("sync", value) : get("sync");
		}		
	}
})();

Settings.load();
